package cn.tedu.blog.server.utils;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.Data;
import lombok.Value;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;


import java.io.InputStream;
import java.util.Arrays;

/**
 * 阿里云对象存储工具类
 */

@Slf4j
public class OssUtils {
    //地域节点

    private static String  endpoint="oss-cn-chengdu.aliyuncs.com";

    //阿里云账号AccessKey
    private static  String accessKeyId = "LTAI5tKYoz9wwZFJCK9XQDYa";

    private static  String accessKeySecret = "5PLOKT7XK9EcotvXyztlcy8aQ99FI0";

    //bucket名称
    private static final String bucketName = "dome1as32465";

    public static String upload(InputStream inputStream, String fileUrl) {
        OSS ossClient = null;
        try {
            //创建OSSClient实例
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //存储对象
            ossClient.putObject(bucketName, fileUrl, inputStream);
        } finally {
            if (ossClient != null) {
                // 关闭OSSClient
                ossClient.shutdown();
            }
        }

        //把新的文件名响应出去
        return "https://"+bucketName+"."+endpoint+"/"+fileUrl;
    }
    public static void delete(String  url){
        if(url!=null){
            String [] u = url.split("/");
            log.error(Arrays.toString(u));
            String objectName=null;
            if(u.length>3){
                objectName = u[3]+"/"+u[4];
                // 创建OSSClient实例。
                OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
                try {
                    // 删除文件或目录。如果要删除目录，目录必须为空。
                    ossClient.deleteObject(bucketName, objectName);
                } catch (OSSException oe) {

                } catch (ClientException ce) {
                } finally {
                    if (ossClient != null) {
                        ossClient.shutdown();
                    }
                }
            }
            }


    }




}
